#include "WIRidle.h"
#include "WIRwalking.h"
#include "GameObject.h"
#include "WanderInRegion.h"
#include "Animation.h"
#include "AudioSource.h"
#include "Logger.h"
#include "Exception.h"

using namespace game_engine;
using namespace game_engine::library;
using namespace game_engine::components;
using namespace game_engine::utils;

///////////////////////////////////////////////////////////////////////////////
// Constructors and Destructors
///////////////////////////////////////////////////////////////////////////////

WIRidle::WIRidle(void)
    : State(), idleTime(0.0f)
{
}

WIRidle::WIRidle(Behaviour *parent, const FLOAT32 max)
    : State(parent)
{
    // The idle time is a random number
    idleTime = (rand() / (RAND_MAX + 1.0f)) * max;
}

WIRidle::~WIRidle(void)
{
}

///////////////////////////////////////////////////////////////////////////////
// Other public methods
///////////////////////////////////////////////////////////////////////////////

void WIRidle::onEnter(void) throw(...)
{
    // Reset sequence time
    Animation *anim;
    try
    {
        anim = dynamic_cast<Animation*> 
            ((fsm->getObject())->getComponent("Animation"));
    } catch (...)
    {
        string msg("[WIRidle::onEnter] animation component not found");
        Logger::ERR(GAMEENGINE_LOG, msg);
        throw RuntimeException(msg);
    }
    anim->resetSequence();
    anim->setActiveSequence(
        dynamic_cast<WanderInRegion*> (fsm)->getIdleAnimationId());

    // Play sound effect
    AudioSource *audio = dynamic_cast<AudioSource*> 
        ((fsm->getObject())->getComponent("AudioSource"));
    audio->play();

    nextState = this;
    dynamic_cast<WanderInRegion*> (fsm)->setIsWalking(false);
}

void WIRidle::onLoop(const FLOAT32 time) throw(...)
{
    // Update IDLE time
    // FIXME
    //idleTime -= time;
    idleTime -= REFRESH_TIME;

    // Check if timeout has expired
    if (idleTime <= 0.0f)
    {
        // Calculate a new destination point within enemy's territory
        Rect r = dynamic_cast<WanderInRegion*> (fsm)->getRegion();

        // Obtain animation component
        Animation *anim;
        anim = dynamic_cast<Animation*> ((fsm->getObject())->getComponent("Animation"));

        Point dest = r.getInternalRandomPoint(anim->getAnchor());
        //std::cout << "new destination point=(" << dest.getX() << "," << dest.getY()
        //    << ")" << std::endl;

        // Change to new state
        nextState = new WIRwalking(fsm, dest);        
    }
}
